package org.weed.remote.network.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.weed.remote.util.ByteUtils;

public class SimpleHttpClient implements Runnable {
	private DefaultHttpClient httpClient;
	private HttpGet httpGet;
	
	public SimpleHttpClient(String url) throws UnknownHostException {		
		httpClient = new DefaultHttpClient();
		
		httpGet = new HttpGet(url);
	}
	
	public void setProxy(String host, int port) {
		HttpHost proxy = new HttpHost(host, port);
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
	}
	
	public void setAuth(String username, String password) throws UnknownHostException {
		String computername = InetAddress.getLocalHost().getHostName();
		Credentials creds = new UsernamePasswordCredentials("ctang@bechtel.com", "Larcenciel0108");
		//new NTCredentials("ctang", "Larcenciel0108", computername, "apac.ibechtel.com");
		
		CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY, creds);
		httpClient.setCredentialsProvider(credentialsProvider);
		
		//NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
		//httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
	}
	
	public void run() {
		try {
			HttpContext localContext = new BasicHttpContext();
			HttpResponse response = httpClient.execute(httpGet, localContext);
			
			AuthState proxyAuthState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
			System.err.println("@"+proxyAuthState.getAuthScope());
			System.err.println("@"+proxyAuthState.getAuthScheme());
			System.err.println(proxyAuthState.getCredentials());
			
			
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String content = EntityUtils.toString(entity);
				System.out.println(content);
			}
			System.out.println("Done!!");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void doURL(String url) {
		try {
			System.setProperty("http.proxyHost", "BNESPROXY");
			System.setProperty("http.proxyPort", "8080");
			URL target = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) target.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoOutput(true);
			
			connection.connect();
			
			Charset charset = Charset.forName("big5");
			CharsetDecoder decoder = charset.newDecoder();
			
			System.out.println(connection.getContentEncoding());
			System.out.println(connection.getContentLength());
			printContent(new BufferedReader(new InputStreamReader(connection.getInputStream(), decoder)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void printContent(BufferedReader reader) {
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				
				int index;
				if ((index = line.indexOf("▽")) >= 0) {
					System.out.println(line.substring(index));
				} else if ((index = line.indexOf("△")) >= 0) {
					System.out.println(line.substring(index));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
        //System.setProperty("java.security.auth.login.config", "login.conf");
        //System.setProperty("java.security.krb5.conf", "krb5.conf");		
        //System.setProperty("sun.security.krb5.debug", "true");
        //System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
		
//		SimpleHttpClient client = new SimpleHttpClient("http://tw.stock.yahoo.com/q/q?s=2498");
//		client.setProxy("BNESPROXY", 8080);
//		client.setAuth("ctang", "Larcenciel0108");
//		client.run();
		
		SimpleHttpClient.doURL("http://tw.stock.yahoo.com/q/q?s=2498");

	}
}
